package com.rm.zeyou.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.constant.NumberConstants;
import com.rm.zeyou.entity.Technician;
import com.rm.zeyou.entity.TechnicianTime;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.TechnicianMapper;
import com.rm.zeyou.mapper.TechnicianTimeMapper;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.TechnicianTimeService;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.util.date.DateUtils;
import com.rm.zeyou.vo.request.UpdateTechnicianTimeVo;
import com.rm.zeyou.vo.request.UserSelectTechnicianTimeVo;
import com.rm.zeyou.vo.response.UserSelectTechnicianTimeResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 技师时间管理表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-12 15:55:09
 */
@Slf4j
@Service
public class TechnicianTimeServiceImpl extends ServiceImpl<TechnicianTimeMapper, TechnicianTime> implements TechnicianTimeService {
    @Resource
    private TechnicianTimeMapper technicianTimeMapper;
    @Resource
    private TechnicianMapper technicianMapper;
    @Resource
    private TechnicianTimeService technicianTimeService;

    @Override
    public ApiRestResponse<List<UserSelectTechnicianTimeResponseVo>> userSelectTechnicianTime(UserSelectTechnicianTimeVo technicianTimeVo) {


        List<UserSelectTechnicianTimeResponseVo> voList = new ArrayList<>();

        List<TechnicianTime> times;
        if ((DateUtil.thisYear() + "-" + technicianTimeVo.getDay()).compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) == 0) {
            log.info("当天时间");
            times = technicianTimeMapper.selectList(new LambdaQueryWrapper<TechnicianTime>()
                    .eq(TechnicianTime::getTechnicianId, technicianTimeVo.getTid())
                    .eq(TechnicianTime::getDay, technicianTimeVo.getDay())
                    .ge(TechnicianTime::getTime, new SimpleDateFormat("HH:mm").format(new Date()))
                    .orderByAsc(TechnicianTime::getTime));
        } else {
            log.info("明天时间");
            times = technicianTimeMapper.selectList(new LambdaQueryWrapper<TechnicianTime>()
                    .eq(TechnicianTime::getTechnicianId, technicianTimeVo.getTid())
                    .eq(TechnicianTime::getDay, technicianTimeVo.getDay())
                    .orderByAsc(TechnicianTime::getTime));
        }
        if (!CheckEmptyUtil.isEmpty(times)) {
            for (TechnicianTime time : times) {
                UserSelectTechnicianTimeResponseVo vo = new UserSelectTechnicianTimeResponseVo();

                vo.setId(time.getId());
                vo.setTime(time.getTime());
                vo.setStatus(time.getStatus());
                voList.add(vo);
            }
        }


        return ApiRestResponse.success(voList);
    }

    @Override
    public ApiRestResponse<List<UserSelectTechnicianTimeResponseVo>> technicianSelectTechnicianTime(Technician technician, UserSelectTechnicianTimeVo technicianTimeVo) {
        List<UserSelectTechnicianTimeResponseVo> voList = new ArrayList<>();
        List<TechnicianTime> times = technicianTimeMapper.selectList(new LambdaQueryWrapper<TechnicianTime>()
                .eq(TechnicianTime::getTechnicianId, technician.getId())
                .eq(TechnicianTime::getDay, technicianTimeVo.getDay())
                .orderByAsc(TechnicianTime::getTime));
        if (!CheckEmptyUtil.isEmpty(times)) {
            for (TechnicianTime time : times) {
                UserSelectTechnicianTimeResponseVo vo = new UserSelectTechnicianTimeResponseVo();

                vo.setId(time.getId());
                vo.setTime(time.getTime());
                vo.setStatus(time.getStatus());
                voList.add(vo);
            }
        }
        return ApiRestResponse.success(voList);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> updateTechnicianTime(Technician technician, UpdateTechnicianTimeVo technicianTimeVo) {
        if (technicianTimeVo.getStatus().equals(NumberConstants.TWO_CONSTANTS)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.PARAM_ERROR);
        }
        TechnicianTime technicianTime = technicianTimeMapper.selectById(technicianTimeVo.getId());
        if (CheckEmptyUtil.isEmpty(technicianTime)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.SERVICE_TIME_EMPTY);
        }
        technicianTime.setStatus(technicianTimeVo.getStatus());

        return ApiRestResponse.success(technicianTimeMapper.updateById(technicianTime));
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void addTechnicianTime() {
        List<Technician> technicianList = technicianMapper.selectList(null);

        if (CheckEmptyUtil.isEmpty(technicianList)) {
            return;
        }

        List<Long> tids = technicianList.stream().map(Technician::getId).collect(Collectors.toList());
        int currentYear = DateUtil.thisYear();


        //清除前一天时间
        String format = new SimpleDateFormat("MM-dd").format(DateUtil.offsetDay(new Date(), -1));
        log.info("前一天时间:{}", format);
        technicianTimeMapper.deleteTechnicianTimeByDate(tids, currentYear, format);

        //添加第三天时间
        List<TechnicianTime> insertList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date thirdDay = DateUtils.addDay(new Date(), 7);
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(thirdDay).concat(" 00:00");
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(thirdDay).concat(" 23:59");


        for (Long tid : tids) {
            List<String> list;
            try {
                Date dBegin = sdf.parse(startDate);
                Date dEnd = sdf.parse(endDate);
                list = DateUtils.findDates("N", dBegin, dEnd, 30);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            for (String str : list) {
                TechnicianTime insertTechnicianTime = new TechnicianTime();
                insertTechnicianTime.setTechnicianId(tid);
                insertTechnicianTime.setYear(currentYear);
                insertTechnicianTime.setDay(str.split(" ")[0]);
                insertTechnicianTime.setTime(str.split(" ")[1]);
                insertTechnicianTime.setStatus(NumberConstants.ZERO_CONSTANTS);
                insertList.add(insertTechnicianTime);
            }

        }

        technicianTimeService.saveBatch(insertList,240);
    }
}
